package codetop.microsoft.T2;

import util.ListNode;

/**
 * @Author: 18362
 * @Create: 2022-08-16 21:55:39 星期二
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null || l2 == null)
            return l1 == null ? l2 : l1;
        ListNode dummy = new ListNode(), p = dummy;
        int carry = 0;
        while (l1 != null && l2 != null) {
            int sum = l1.val + l2.val + carry;
            p.next = new ListNode(sum % 10);
            carry = sum / 10;
            p = p.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        ListNode q = l1 == null ? l2 : l1;
        while (q != null) {
            int sum = q.val + carry;
            p.next = new ListNode(sum % 10);
            carry = sum / 10;
            p = p.next;
            q = q.next;
        }
        if (carry != 0) {
            p.next = new ListNode(carry);
        }
        return dummy.next;
    }
}